package com.test.deencredit.analytics_deencredit.util_deencredit

import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import com.google.android.play.core.review.ReviewException
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory
import com.google.android.play.core.review.model.ReviewErrorCode

/**
 * 评分模块
 * 1、首先需要集成:
 * implementation("com.google.android.play:review-ktx:2.0.1")
 */
object ApRvUtil_deencredit {

    private var mReviewManager_deencredit: ReviewManager? = null

    private var mReviewInfo_deencredit: ReviewInfo? = null

    /**
     * 初始化评分模块
     *
     * @param context Application
     */
    fun iniAprvutil_deencredit(context: Application) {
        mReviewManager_deencredit = ReviewManagerFactory.create(context)
        val request = mReviewManager_deencredit?.requestReviewFlow()
        request?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                // 缓存起来，一般2小时内有效，能满足业务需要
                mReviewInfo_deencredit = task.result

            } else {
                @ReviewErrorCode
                val reviewErrorCode = (task.getException() as ReviewException).errorCode
                when (reviewErrorCode) {
                    ReviewErrorCode.NO_ERROR -> {
                        println("reviewErrorCode: NO_ERROR")
                    }
                    ReviewErrorCode.PLAY_STORE_NOT_FOUND -> {
                        println("reviewErrorCode: PLAY_STORE_NOT_FOUND")
                    }
                    ReviewErrorCode.INVALID_REQUEST -> {
                        println("reviewErrorCode: INVALID_REQUEST")
                    }
                    ReviewErrorCode.INTERNAL_ERROR -> {
                        println("reviewErrorCode: INTERNAL_ERROR")
                    }
                    else -> {
                        println("reviewErrorCode: UNKNOW")
                    }
                }
            }
        }
    }

    /**
     * 调起评分流程
     *
     * @param activity Activity
     * @param completed 结束回调，收到回调后，继续走app流程
     */
    fun launchRvFlow_deencredit(activity: AppCompatActivity, completed: (Boolean) -> Unit) {
        //如果为空，直接返回
        if (mReviewInfo_deencredit == null) {
            completed.invoke(false)
        }

        //非空执行
        mReviewInfo_deencredit?.let {
            //调起评分
            val flow = mReviewManager_deencredit?.launchReviewFlow(activity, it)

            //如果为空，直接返回
            if (flow == null) {
                completed.invoke(false)
            }

            flow?.addOnCompleteListener {
                completed.invoke(true)
            }
        }
    }

}